/**
 * 版权所有 (C), 2019-2019, XXX有限公司
 * 项目名：com.company.study.dsa.queue
 * 文件名: DoubleQueue
 * 日期: 2019/6/17 21:46
 * 说明:
 */
package com.company.study.dsa.queue;

/**
 * 双端队列
 *
 * @author Anbang713
 * @create 2019/6/17
 */
public class DoubleQueue {
    private Object[] array;
    //队列总大小
    private int maxSize;
    //前端
    private int front;
    //后端
    private int rear;
    //队列中元素的实际数目
    private int itemSize;

    public DoubleQueue(int maxSize) {
        this.maxSize = maxSize;
        array = new Object[maxSize];
        front = 0;
        rear = -1;
        itemSize = 0;
    }

    public boolean isFull() {
        return itemSize == maxSize;
    }

    public boolean isEmpty() {
        return itemSize == 0;
    }

    public int getSize() {
        return itemSize;
    }

    /**
     * 返回对头元素
     *
     * @return
     */
    public Object peekFront() {
        return array[front];
    }

    /**
     * 向队尾插入数据
     *
     * @param value
     * @return true表示成功插入，false表示失败
     */
    public boolean insertRight(Object value) {
        if (isFull()) {
            System.out.println("队列已满。");
            return false;
        }
        if (rear == maxSize - 1) {
            rear = -1;
        }
        array[++rear] = value;
        itemSize++;
        return true;
    }

    /**
     * 向队头插入数据
     *
     * @param value
     * @return true表示成功插入，false表示失败
     */
    public boolean insertLeft(Object value) {
        if (isFull()) {
            System.out.println("队列已满。");
            return false;
        }
        if (front == 0) {
            front = maxSize;
        }
        array[--front] = value;
        itemSize++;
        return true;
    }

    /**
     * 删除队尾数据
     *
     * @return 被删除的数据
     */
    public Object removeRight() {
        Object removeValue = null;
        if (isEmpty()) {
            System.out.println("队列已空。");
            return removeValue;
        }
        removeValue = array[rear];
        array[rear--] = null;
        if (rear == -1) {
            rear = maxSize - 1;
        }
        itemSize--;
        return removeValue;
    }

    /**
     * 删除队头数据
     *
     * @return 被删除的数据
     */
    public Object removeLeft() {
        Object removeValue = null;
        if (isEmpty()) {
            System.out.println("队列已空。");
            return removeValue;
        }
        removeValue = array[front];
        array[front++] = null;
        if (front == maxSize) {
            front = 0;
        }
        itemSize--;
        return removeValue;
    }

    public void display() {
        int min = front < rear ? front : rear;
        int max = front < rear ? rear : front;
        for (int i = min; i <= max; i++) {
            if (array[i] != null) {
                System.out.print(array[i] + " ");
            }
        }
        System.out.println();
    }
}